import React, { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
  ReadFilled,
  EditFilled,
  MinusOutlined,
  FullscreenOutlined,
  CloseOutlined,
} from '@ant-design/icons'
import { message } from 'antd'
import styles from './index.module.less'
import store from '@/redux/store'
import { updateHarvestInfoAction } from '@/redux/action/harvestInfo'
import { getHarvestDetailApi } from '@/request/api/harvest'

//
// 头部部分
export default function Header() {
  // 窗口最小化
  const minWindow = () => (window as any).readingWindow.minWindow()
  // 窗口最大化切换
  const maxWindow = () => (window as any).readingWindow.maxWindow()
  // 关闭窗口
  const closeWindow = () => (window as any).readingWindow.closeWindow()

  const navitate = useNavigate()

  // 页面跳转
  const jumperRead = () => navitate('/read')
  const jumperEdit = () => navitate('/edit')

  const [harvestId, setHarvestId] = useState<string>(
    store.getState().harvestInfoReducer.harvestId
  )

  useEffect(() => {
    const unsubscribe = store.subscribe(() => {
      setHarvestId(store.getState().harvestInfoReducer.harvestId)
    })

    jumperRead()

    return () => {
      unsubscribe()
    }
  }, [])

  useEffect(() => {
    if (harvestId) getHarvestDetail()
  }, [harvestId])

  // 获取收获的详细信息
  const getHarvestDetail = async () => {
    const res = await getHarvestDetailApi(harvestId)

    if (res.code !== 200) return message.error('获取收获详情失败！')

    // message.success('获取收获详情成功！')
    const { description } = res.data
    store.dispatch(updateHarvestInfoAction({ description }))
  }

  return (
    <div className={styles.headerContainer}>
      <div className={styles.toggleBtns}>
        <ReadFilled
          title='阅读收获笔记'
          style={{ fontSize: '18px' }}
          onClick={jumperRead}
        />
        <EditFilled
          title='创建新的示例'
          style={{ fontSize: '18px' }}
          onClick={jumperEdit}
        />
      </div>

      <div className={styles.label}>收获详情</div>

      <div className={styles.controlBtns}>
        <MinusOutlined style={{ fontSize: '20px' }} onClick={minWindow} />
        <FullscreenOutlined style={{ fontSize: '20px' }} onClick={maxWindow} />
        <CloseOutlined style={{ fontSize: '20px' }} onClick={closeWindow} />
      </div>
    </div>
  )
}
